﻿using System.Text.Json.Serialization.Metadata;
using DimensionsHelper.Common.Utils;

namespace DimensionsHelper.ExcelAddIn.Core;

public class LocalSettingService<T> where T : new()
{

    static LocalSettingService()
    {
        if (!Directory.Exists(ExcelAddInEnv.UserDataFolder))
        {
            Directory.CreateDirectory(ExcelAddInEnv.UserDataFolder);
        }
    }


    private readonly string _localFolderName;
    private readonly string _defaultSettingsName = "";
    private readonly Dictionary<string, T> _cached = new(StringComparer.OrdinalIgnoreCase);
    private readonly JsonTypeInfo<T> _jsonTypeInfo;
    private T _default;


    public LocalSettingService(string section, JsonTypeInfo<T> jsonTypeInfo)
    {
        _localFolderName = Path.Combine(ExcelAddInEnv.UserDataFolder, section);
        if (!Directory.Exists(_localFolderName))
        {
            Directory.CreateDirectory(_localFolderName);
        }

        _defaultSettingsName = $"{ExcelAddInEnv.DefaultSettingName}.json";
        _jsonTypeInfo = jsonTypeInfo;
        _default = new T();

        Initialize();
    }


    private void Initialize()
    {
        foreach (var file in Directory.GetFiles(_localFolderName))
        {
            // 忽略默认设置文件和非.json扩展名的文件
            if (file.Equals(_defaultSettingsName, StringComparison.OrdinalIgnoreCase) ||
                !Path.GetExtension(file).Equals(".json", StringComparison.OrdinalIgnoreCase))
            {
                return;
            }

            var settings = JsonHelper.ReadJson(file, _jsonTypeInfo);
            if (settings != null)
            {
                var fileName = Path.GetFileNameWithoutExtension(file);
                _cached[fileName] = settings;
            }
        }

        // 初始化默认设置
        string defaultSettingPath = Path.Combine(_localFolderName, _defaultSettingsName);
        if (File.Exists(defaultSettingPath))
        {
            _default = JsonHelper.ReadJson(defaultSettingPath, _jsonTypeInfo) ?? new T();
            return;
        }

        JsonHelper.WriteJson(_default, _jsonTypeInfo, defaultSettingPath);
    }


    /// <summary>
    ///     判断指定的设置对象名是否为默认设置
    /// </summary>
    /// <param name="name">配置名</param>
    public bool IsDefaultSetting(string name) => name.Equals(_defaultSettingsName);


    /// <summary>
    ///     获取已读取的设置对象名数组
    /// </summary>
    public string[] SettingNames => _cached.Keys.Where(k => !IsDefaultSetting(k)).ToArray();


    /// <summary>
    ///     获取默认的设置对象
    /// </summary>
    public T Default => _default;


    /// <summary>
    ///     保存指定命名的设置对象
    /// </summary>
    /// <param name="settingName">设置名</param>
    /// <param name="settings">新的设置对象</param>
    /// <param name="asDefault">是否同时设置为默认设置</param>
    public void Save(string settingName, T settings, bool asDefault = false)
    {
        var fileName = Path.Combine(_localFolderName, $"{settingName}.json");
        JsonHelper.WriteJson(settings, _jsonTypeInfo, fileName);
        _cached[settingName] = settings;

        if (!asDefault)
        {
            return;
        }

        _default = settings;
        JsonHelper.WriteJson(settings, _jsonTypeInfo, Path.Combine(_localFolderName, _defaultSettingsName));
    }


    /// <summary>
    ///     载入指定命名的设置对象
    /// </summary>
    /// <param name="settingName">设置名</param>
    /// <returns>解析后的JSON对象，如果文件不存在或解析失败，返回<see langword="default"/></returns>
    public T? Load(string settingName)
    {
        var fileName = Path.Combine(_localFolderName, $"{settingName}.json");

        if (!File.Exists(fileName))
        {
            return default;
        }

        var settings = JsonHelper.ReadJson(fileName, _jsonTypeInfo);
        if (settings != null)
        {
            _cached[settingName] = settings;
        }

        return settings;
    }

}
